import './index.scss'
import { DownOutlined } from '@ant-design/icons'
import ShuaxinImg from '@/assets/shuaxin.png'
import {
  Row, Col, Tabs, Space, Dropdown, message, Popconfirm, Table
  // , Tooltip, List, Button
  // List , 
  // Radio
} from 'antd'
import React, {
  useEffect, useState, useRef, useCallback, useLayoutEffect
} from 'react'
import { http, baseUrlWs, getToken } from '@/utils'
import { Link, useNavigate } from 'react-router-dom'

import { useStore } from '@/store'
// import VirtualList from 'rc-virtual-list'
import { Scrollbars } from 'react-custom-scrollbars'
// import Tmptransfer from './components/Tmptransfer'
import OrderModalopen from './components/Ordermodalopen'
const Panel = () => {
  const { loginStore } = useStore()
  const [tabsData, setTabsData] = useState([])
  const tabsDataRef = useRef([])
  // const [listData, setListData] = useState([])
  const [configModalData, setConfigModalData] = useState({
    configModalOpen: false,
    configModalRow: {}
  })
  // const [configModalRow, setConfigModalRow] = useState({})

  // const listDataRef = useRef()
  const [waningData, setWaningData] = useState([])
  const ws = useRef(WebSocket | null) // WebSocket 对象
  const readyState = useRef()
  const groupIdRef = useRef(null)
  const waningDataRef = useRef([])

  const [showType, setShowType] = useState(1)
  const [showListId, setShowListId] = useState('')
  // const [visible, setVisible] = useState(false) //菜单显隐藏
  // const [featureId, setFeatureId] = useState(null)
  // const [waningId, setWaningId] = useState(null)
  // const [scrollLoad, setScrollLoad] = useState(true)
  const maxHeight = document.body.offsetHeight - 200
  // const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [delBtnDis, setDelBtnDis] = useState(true)
  const [unTabsData, setUnTabsData] = useState([])

  const [params, setParams] = useState({
    userId: loginStore.userId,
    pageNum: 1,
    pageSize: 50
  })
  const [varietyData, setVarietyData] = useState({
    list: [],
    count: 0
  })
  // const [total, setTotal] = useState(1000)
  // const [selectedAlarmGroupByFeatureId, setSelectedAlarmGroupByFeatureId] = useState([])
  // const contextMenu = useRef(null) //ref
  // 配置品种预警组
  // let ChildRef = React.createRef()
  // const showModalOpen = () => {
  //   const row = waningData.filter(item => item.id + '' === waningId)[0]
  //   setVisible(false)
  //   ChildRef.current.openConfigModalOpen(row)
  // }
  // const changeConfigModal = (msg) => {
  // console.log('子组件调用：' + msg)
  // }
  // 下单
  let OrderRef = React.createRef()
  const showOrderModalOpen = (e, item) => {
    const row = {
      ...item,
      featureName: item.featureName ? item.featureName : item.displayName,
      featureCode: item.featureCode ? item.featureCode : item.scode
    }
    OrderRef.current.openConfigModalOpen(row)
  }
  const changeConfigModal = (msg) => {
    setConfigModalData({
      configModalOpen: false,
      configModalRow: {}
    })
    console.log('子组件调用：' + msg)
  }
  const tabsOnChange = async (activeKey) => {
    let groupId = null
    const list = tabsDataRef.current.map(item => {
      const row = { ...item }
      if (item.key === activeKey) {
        row.badge = 0
        groupId = item.groupId
        groupIdRef.current = item.groupId
      }
      return row
    })
    setTabsData(list)
    tabsDataRef.current = list
    setParams({
      ...params,
      pageNum: 1,
      groupId
    })
  }
  const btnOnClick = (typeKey) => {
    setParams({
      ...params,
      pageNum: 1
    })
    setShowType(typeKey)
  }
  const listOnClick = (id) => {
    let list = []
    if (showType === 1) {
      list = varietyData.list.filter(item => item.id === id)
    } else {
      list = waningData.filter(item => item.id === id)
    }
    console.log('调用客户端api', JSON.stringify(list[0]))
    try {
      window.QCefWidget.invoke('postClient', JSON.stringify(list[0]))
    } catch (error) {
      console.warn('当前环境不支持，请在看盘客户端内选中')
    }
    setShowListId(id)
  }
  let [firstOnload, setFirstOnload] = useState(true)

  let timer2 = useRef()
  const webSocketInit = useCallback(() => {
    const stateArr = [
      '正在链接中...',
      '已经链接并且可以通讯',
      '连接正在关闭',
      '连接失败，请尝试重新连接',
    ]
    let heartbeat = 0
    // let timer = null
    timer2.current = setInterval(() => {
      console.log(heartbeat)
      if (heartbeat >= 10 && ws.current.readyState !== 1) {
        heartbeat = 0
        clearTimeout(timer2.current)
        webSocketInit()
      }
      heartbeat += 1
    }, 1000)
    if (!ws.current || ws.current.readyState === 3) {
      // ws.current = new WebSocket(`ws://192.168.12.105:7070?token=${getToken()}`)  // 本地测试
      ws.current = new WebSocket(`${baseUrlWs}alarm/webSocket?token=${getToken()}`)
      ws.current.onopen = _e => {
        readyState.current = stateArr[ws.current?.readyState ?? 0]
        // message.destroy()
        // message.success(stateArr[ws.current?.readyState ?? 0])
        return console.log('连接成功')
      }
      ws.current.onclose = _e => {
        readyState.current = stateArr[ws.current?.readyState ?? 0]
        // message.warning(stateArr[ws.current?.readyState ?? 0])
        return console.log('已断开', _e)
      }
      ws.current.onerror = e => {
        readyState.current = stateArr[ws.current?.readyState ?? 0]
        // message.warning(stateArr[ws.current?.readyState ?? 0])
        // clearTimeout(timer2.current)
        return console.log('error', e)
      }
      ws.current.onmessage = e => {
        heartbeat = 0
        const body = JSON.parse(e.data)
        // 更新未读信息数量 当前预警分组下的预警信息  且userIds必须包含当前用户
        for (let index = 0; index < tabsDataRef.current.length; index++) {
          const element = tabsDataRef.current[index]
          const cList = body.filter(litem => {
            if (
              litem.groupId === element.groupId &&
              +litem.groupId !== +groupIdRef.current &&
              litem.userIds.indexOf(+loginStore.userId) !== -1
            ) {
              return true
            }
            return false
          })
          element.badge = element.badge + cList.length
        }

        // 推送到当前预警组信号 且userIds必须包含当前用户
        const list = body.filter(item => {
          return +item.groupId === +groupIdRef.current && item.userIds.indexOf(+loginStore.userId) !== -1
        })
        const new_list = [
          ...list.map((item, i) => ({
            ...item,
            scode: item.featureCode,
            id: `${i}_${new Date().getTime()}`,
            direction: item.factorName.indexOf('⬇') !== -1 ? 1 : 0,
            factorName: item.factorName.replace(/⬇|⬆/g, "")
          }
          )),
          ...waningDataRef.current
        ].splice(0, 50)
        if (list.length) {
          console.log(list, new_list)
        }
        waningDataRef.current = new_list
        setWaningData(new_list)
      }
    } else {
      heartbeat = 0
      console.log('浏览器不支持WebSocket')
    }
  }, [loginStore])
  // 获取可编辑预警组
  const getDropList = async (e, featureId) => {
    const res = await http.post('/alarm/deliversign/getSelectedAndUnSelectedAlarmGroupByFeatureId', {
      userId: loginStore.userId,
      featureId: featureId,
      groupAlarmName: ""
    })
    const list = tabsData.filter(item => item.groupId === groupIdRef.current)[0]
    let btnDis = true
    const myGroupList = res.body.selectedAlarmGroupByFeatureId ? res.body.selectedAlarmGroupByFeatureId.filter(item => {
      return +item.createdBy === +loginStore.userId
    }) : []
    if (myGroupList) {
      for (let index = 0; index < myGroupList.length; index++) {
        const element = myGroupList[index]
        if (element.id === list.groupId) {
          btnDis = false
        }
      }
    }
    setDelBtnDis(btnDis)
    setUnTabsData(res.body.unSelectedAlarmGroupByFeatureId)
  }


  useEffect(() => {
    // 获取用户预警组
    const getTabs = async () => {
      const res = await http.post('/alarm/deliversign/getAlarmGroupByUserId', { userId: params.userId })
      setFirstOnload(false)
      const list = res.body.map(item => {
        const row = {
          label: item.groupAlarmName,
          createdBy: item.createdBy,
          badge: 0,
          key: `_${item.id}`,
          groupId: item.id,
          children: `children${item.id}}`
        }
        return row
      })
      console.log('用户预警组', list)
      tabsDataRef.current = list
      setTabsData(list)
      if (list.length) {
        groupIdRef.current = list[0].groupId
        setParams({
          ...params,
          groupId: list[0].groupId
        })
      }
    }
    /**下单 删除 添加到 */
    const getDropListEffect = async (e, featureId) => {
      const res = await http.post('/alarm/deliversign/getSelectedAndUnSelectedAlarmGroupByFeatureId', {
        userId: loginStore.userId,
        featureId: featureId,
        groupAlarmName: ""
      })
      const list = tabsData.filter(item => item.groupId === groupIdRef.current)[0]
      let btnDis = true
      const myGroupList = res.body.selectedAlarmGroupByFeatureId ? res.body.selectedAlarmGroupByFeatureId.filter(item => {
        return +item.createdBy === +loginStore.userId
      }) : []
      if (myGroupList) {
        for (let index = 0; index < myGroupList.length; index++) {
          const element = myGroupList[index]
          if (element.id === list.groupId) {
            btnDis = false
          }
        }
      }
      setDelBtnDis(btnDis)
      console.log(res.body.unSelectedAlarmGroupByFeatureId)
      setUnTabsData(res.body.unSelectedAlarmGroupByFeatureId)
    }
    // 快速添加删除
    const configVarietyEffect = async (type, row, tabsRow) => {
      const data = {
        setType: type,
        featureCode: row.featureCode || row.scode
      }
      // // 删除
      if (type === 0) {
        const list = tabsData.filter(item => item.groupId === groupIdRef.current)
        data.alarmGroupId = list[0].groupId
        data.alarmGroupText = list[0].label
      }
      // // 添加
      if (type === 1) {
        data.alarmGroupId = tabsRow.id
        data.alarmGroupText = tabsRow.groupAlarmName
      }
      // console.log(data)
      const res = await http.post('/alarm/deliversign/quickAddAlarmGroupIntoFeature', data)
      message.success(res.body)
      if (type === 0) {
        getAlarmGroupData()
      }
    }
    const showOrderModalOpenEffect = (e, item) => {
      const row = {
        ...item,
        featureName: item.featureName ? item.featureName : item.displayName,
        featureCode: item.featureCode ? item.featureCode : item.scode,
        freqName: ''
      }
      setConfigModalData({
        configModalOpen: true,
        configModalRow: row
      })
    }
    /** end */
    const getFreq = async () => {
      const res = await http.post('/alarm/deliversign/getAllFreq')
      const vList = res.body ? [{
        value: 'total_score',
        freqName: '总分',
        freqKey: 'totalScore',
      }, ...res.body] : []
      const list = vList.map(item => ({
        dataIndex: item.freqKey,
        value: item.value,
        label: item.freqName,
        freqKey: item.freqKey,
        title: item.freqName,
        align: 'center',
        width: 70,
        sorter: true,
        render: (data, item) => {
          return (<>
            <Dropdown
              onOpenChange={(e) => getDropListEffect(e, item.id)}
              menu={{
                items: [
                  { label: '删除', key: '1', disabled: delBtnDis, onClick: (e) => configVarietyEffect(0, item) },
                  { label: '下单', key: '3', onClick: (e) => showOrderModalOpenEffect(0, item) },
                  {
                    label: '添加到', key: '2', children: unTabsData.map(titem => {
                      return {
                        label: titem.groupAlarmName,
                        key: titem.id,
                        onClick: (e) => configVarietyEffect(1, item, titem)
                      }
                    })
                  }
                ],
              }}
              trigger={['contextMenu']}
            >
              <div style={{ padding: 5 }}>
                {data === null ? '-' : data}
              </div>
            </Dropdown>
          </>)
        }
      }))
      console.log('周期列表-', list)

      setColumns([
        {
          title: '品种代码',
          dataIndex: '',
          width: 200,
          fixed: 'left',
          render: (data) => {
            return <div>
              <Dropdown
                destroyPopupOnHide={true}
                key={data.id}
                onOpenChange={(e) => getDropListEffect(e, data.id)}
                menu={{
                  items: [
                    { label: '删除', key: '1', disabled: delBtnDis, onClick: (e) => configVarietyEffect(0, data) },
                    { label: '下单', key: '3', onClick: (e) => showOrderModalOpenEffect(0, data) },
                    {
                      label: '添加到', key: '2', children: unTabsData.map(titem => {
                        return {
                          label: titem.groupAlarmName,
                          key: titem.id,
                          onClick: (e) => configVarietyEffect(1, data, titem)
                        }
                      })
                    }
                  ],
                }}
                trigger={['contextMenu']}
              >
                <div style={{ padding: 5 }}>
                  <Space>
                    <div>{data.displayName}</div>
                    <div>{data.scode.split('.')[0]}</div>
                  </Space>
                </div>
              </Dropdown>

            </div>

          }
        },
        ...list
      ])
    }

    // 获取用户预警组品种
    const getAlarmGroupData = async () => {
      const res = await http.post('/alarm/deliversign/findFeatureInfoByPage', params)
      console.log('品种池列表-', res.body)
      const { list, total } = res.body
      setVarietyData({
        list: list,
        count: total
      })
      getFreq()
      // const list = res.body.list.map(item => {
      //   return item
      // })
      console.log('预警组品种', list)
      if (list.length) {
        setShowListId(list[0].id)
      }
      // setScrollLoad(true)
      // setTotal(res.body.total)
      // if (params.pageNum === 1) {
      // listDataRef.current = list
      // setListData(list)
      // } else {
      // listDataRef.current = [...listDataRef.current, ...list]
      // setListData(listDataRef.current)
      // }
      // alert(JSON.stringify(list))
    }

    // 获取预警历史记录
    const getHistorical = async (item) => {
      http.post('/alarm/deliversign/findTbUserAlarmInfosByUserId', params).then(res => {
        const list = res.body.list.map(citem => {
          return {
            ...citem,
            scode: citem.featureCode,
            direction: citem.factorName.indexOf('⬇') !== -1 ? 1 : 0,
            factorName: citem.factorName.replace(/⬇|⬆/g, "")
          }
        })
        console.log('预警组历史预警信号', list)
        waningDataRef.current = list
        setWaningData(list)
      })
    }
    if (firstOnload) {
      getTabs()
    } else {
      if (showType === 1) {
        getAlarmGroupData()
      } else {
        getHistorical()
      }
    }
    return
  }, [loginStore, firstOnload, showType, params, tabsData, delBtnDis, unTabsData])

  // 获取用户预警组品种
  const getAlarmGroupData = async () => {
    const res = await http.post('/alarm/deliversign/findFeatureInfoByPage', params)
    const list = res.body.list.map(item => {
      return item
    })
    console.log('预警组品种', list)
    if (list.length) {
      setShowListId(list[0].id)
    }
    // setScrollLoad(true)
    // setTotal(res.body.total)
    // if (params.pageNum === 1) {
    // listDataRef.current = list
    // setListData(list)
    // } else {
    // listDataRef.current = [...listDataRef.current, ...list]
    // setListData(listDataRef.current)
    // }
    // alert(JSON.stringify(list))
  }
  // 快速添加删除
  const configVariety = async (type, row, tabsRow) => {
    const data = {
      setType: type,
      featureCode: row.featureCode || row.scode
    }
    // 删除
    if (type === 0) {
      const list = tabsData.filter(item => item.groupId === groupIdRef.current)
      data.alarmGroupId = list[0].groupId
      data.alarmGroupText = list[0].label
    }
    // 添加
    if (type === 1) {
      data.alarmGroupId = tabsRow.id
      data.alarmGroupText = tabsRow.groupAlarmName
    }
    console.log(data)
    const res = await http.post('/alarm/deliversign/quickAddAlarmGroupIntoFeature', data)
    message.success(res.body)
    if (type === 0) {
      getAlarmGroupData()
    }
  }

  /** 
  * 初始化 WebSocket
  * 且使用 WebSocket 原生方法获取信息
  *  
  **/
  useLayoutEffect(() => {
    webSocketInit()
    return () => {
      ws.current?.close()
      clearTimeout(timer2.current)
    }
  }, [ws, webSocketInit])
  const [columns, setColumns] = useState([])
  const onSortChange = (pagination, filters, sorter) => {
    const orderByInfo = {}
    if (sorter.column) {
      orderByInfo[sorter.column.freqKey] = sorter.order ? sorter.order.replace('end', '') : ''
    }
    setParams({
      ...params,
      orderByInfo,
      pageSize: pagination.pageSize,
      pageNum: pagination.current
    })
  }
  // const onScroll = (e) => {
  //   const height = e.target.scrollTop + e.target.clientHeight
  //   const num = params.pageNum + 1
  //   if (height >= e.target.firstChild.clientHeight && scrollLoad && num <= Math.ceil(total / params.pageSize)) {
  //     setParams({
  //       ...params,
  //       pageNum: num
  //     })
  //     console.log('到底部,加载第二页信息')
  //     setScrollLoad(false)
  //   }
  // }
  const renderThumb = () => { // renderThumb改变样式时被调用的函数，必须是函数
    const thumbStyle = { // 设置滚动条样式
      backgroundColor: 'rgba(255,255,255,0.5)',
      borderRadius: '4px'
    }
    return <div style={{ ...thumbStyle }} />
  }
  // 确定退出
  const navigate = useNavigate()
  const onConfirm = () => {
    // 退出登录 删除token 跳回到登录
    loginStore.loginOut()
    navigate('/login?')
  }
  return (
    <>
      <div className='container'>
        <Space align="baseline" style={{ width: '100%', justifyContent: 'space-between' }}>
          <div style={{ lineHeight: '30px' }}>
            <span style={{ margin: '0 10px' }}>预警平台</span>
            <img
              onClick={() => { window.location.reload() }}
              src={ShuaxinImg}
              title='刷新'
              style={{ width: 18, height: 18, verticalAlign: 'text-bottom', cursor: 'pointer' }}
              alt="1"
            />
          </div>
          <div>
            <span>{loginStore.userName}</span>
            <Popconfirm
              onConfirm={onConfirm}
              title="是否确认退出？" okText="退出" cancelText="取消">
              <span className='link' style={{ margin: '0 10px' }}>退出</span>
            </Popconfirm>

          </div>
        </Space>
        {tabsData.length ? '' : <Link to='/historical' style={{ color: "#fff" }}>首页</Link>}
        <Row>
          <Col span={24}>
            <Tabs
              type='card'
              size='small'
              centered
              animated={false}
              moreIcon={(<div style={{ width: 80 }}>更多预警 <DownOutlined /></div>)}
              tabBarGutter={0}
              onChange={tabsOnChange}
              className='panelTabs'
              items={tabsData.map((item, i) => {
                return {
                  label: item.badge > 0 ? <div>
                    <span className='panelBadge'>{item.badge > 99 ? '+99' : item.badge}</span>
                    <span> {item.label}</span>
                  </div> : <div>
                    <span>{item.label}</span>
                  </div>,
                  key: item.key,
                  children: (
                    <>
                      <Row>
                        <Col span={12}><div className={`btn ${showType === 1 ? 'active' : ''}`} onClick={() => btnOnClick(1)}>品种</div></Col>
                        <Col span={12}><div className={`btn ${showType === 2 ? 'active' : ''}`} onClick={() => btnOnClick(2)}>信号</div></Col>
                      </Row>
                      {showType === 2 ? <div className='panelList waningList'>
                        <Row className='header'>
                          <Col span={9} style={{ paddingLeft: 5 }}>品种名称</Col>
                          <Col span={4}>预警周期</Col>
                          <Col span={3}>总分</Col>
                          <Col span={8}>预警因子</Col>
                        </Row>
                        <Scrollbars
                          style={{ height: 'calc(100vh - 150px)' }}
                          renderThumbVertical={renderThumb}
                        >
                          <div>
                            {waningData.map(citem => (<Dropdown
                              key={citem.id}
                              onOpenChange={(e) => getDropList(e, citem.featureId)}
                              menu={{
                                items: [
                                  { label: '删除', key: '1', disabled: delBtnDis, onClick: (e) => configVariety(0, citem) },
                                  { label: '下单', key: '3', onClick: (e) => showOrderModalOpen(0, citem) },
                                  {
                                    label: '添加到', key: '2', children: unTabsData.map(titem => {
                                      return {
                                        label: titem.groupAlarmName,
                                        key: titem.id,
                                        onClick: (e) => configVariety(1, citem, titem)
                                      }
                                    })
                                  }
                                ],
                              }}
                              trigger={['contextMenu']}
                            >
                              <Row
                                className={`${citem.id === showListId ? 'active item' : 'item'}`}
                                onClick={() => listOnClick(citem.id)}
                              // title={citem.freqName + '：' + citem.score + '\n'}
                              >
                                <Col span={9} style={{ paddingLeft: 5, lineHeight: '15px', marginTop: 7 }}>
                                  <div waning={citem.id} style={{ color: 'rgba(255, 255, 255, 0.30)', fontSize: '12px' }}>{citem.datetime}</div>
                                  <div waning={citem.id}>
                                    <span>{citem.featureName}</span>
                                    {citem.marginTrading ? <span className='trading'>融</span> : ''}
                                  </div>
                                </Col>
                                <Col span={4}><div waning={citem.id}>{citem.freqName}</div></Col>
                                <Col span={3}><div waning={citem.id}>{citem.score}</div></Col>
                                <Col span={8}><div waning={citem.id} style={{ lineHeight: '15px', marginTop: 7 }}>
                                  {citem.factorName}
                                  {citem.direction ? <svg className="icon" aria-hidden="true" style={{ color: '#00E600' }}>
                                    <use xlinkHref="#icon-paixu"></use>
                                  </svg> : <svg className="icon" aria-hidden="true" style={{ color: '#FF3232' }}>
                                    <use xlinkHref="#icon-xiangshang"></use>
                                  </svg>}
                                </div></Col>
                              </Row>
                            </Dropdown>
                            ))}
                          </div>
                        </Scrollbars>
                      </div> : <Table
                        onRow={(data) => {
                          return {
                            onClick: (e) => {
                              const list = varietyData.list.map(item => {
                                const row = item
                                if (row.id === data.id) {
                                  item.active = true
                                } else {
                                  item.active = false
                                }
                                return row
                              })
                              setVarietyData({
                                list,
                                count: varietyData.count
                              })
                              listOnClick(data.id)
                            }
                          }
                        }}
                        bordered={false}
                        style={{ background: '#fff' }}
                        scroll={{
                          x: 700,
                          y: maxHeight
                        }}
                        rowClassName={(record, index) => {
                          if (record.active) {
                            return "blackRow rowActive"
                          }
                          return "blackRow"
                        }}
                        rowKey="id"
                        size='small'
                        columns={columns}
                        dataSource={varietyData.list}
                        onChange={onSortChange}
                        pagination={
                          {
                            size: 'small',
                            showQuickJumper: false,
                            showSizeChanger: false,
                            pageSize: params.pageSize,
                            total: varietyData.count,
                            current: params.pageNum,
                            showTotal: (total, range) => `共 ${total} 条`,
                          }
                        }
                      />
                      }
                    </>
                  )
                }
              })}
            />
          </Col>
        </Row>
      </div>
      {/* <div ref={contextMenu} className={`contextMenu`} style={{ display: visible ? 'block' : 'none' }}>
          <div className={`menuList`} onClick={configVariety}>删除</div>
          <div className={`menuList`} onClick={showOrderModalOpen}>下单</div>
          <div className={`menuList`} onClick={configVariety}>配置预警组</div>
        </div> */}
      {/* <Tmptransfer tabsData={tabsData} onRef={ChildRef} changeConfigModal={changeConfigModal} /> */}
      <OrderModalopen
        tabsData={tabsData}
        onRef={OrderRef}
        configModalData={configModalData}
        changeConfigModal={changeConfigModal}
      />
    </>
  )
}

export default Panel